<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas randou</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
  </body>
  <script>
    const canvasDom = document.getElementById('canvas')
    canvasDom.width = window.innerWidth
    canvasDom.height = window.innerHeight
    const ctx = canvasDom.getContext('2d')
    // 存储已有的圆环数组
    var circles = []
    const maxTimes = 1000

    // 循环生成不同大小不同颜色的圆环
    for (var i = 0; i < 500; i++) {
      // 生成随机半径和颜色
      var radius = Math.random() * 50 + 10
      var color = '#' + (((1 << 24) * Math.random()) | 0).toString(16)

      // 生成随机圆心坐标
      var x = Math.random() * canvasDom.width
      var y = Math.random() * canvasDom.height
      let times = 0
      // 检查圆环是否和已有的圆环有重叠部分
      while (isOverlap(x, y, radius, circles) && ++times < maxTimes) {
        console.log(`isOverlap${i}`, times);
        x = Math.random() * canvasDom.width
        y = Math.random() * canvasDom.height
      }
      if (times >= maxTimes) continue 
      // 存储新的圆环信息到数组中
      circles.push({ x: x, y: y, radius: radius })

      // 绘制圆环
      ctx.beginPath()
      ctx.arc(x, y, radius, 0, 2 * Math.PI)
      ctx.strokeStyle = color
      ctx.lineWidth = 5
      ctx.stroke()
    }

    // 判断圆环是否和已有的圆环有重叠部分
    function isOverlap(x, y, radius, circles) {
      for (var i = 0; i < circles.length; i++) {
        var distance = Math.sqrt(
          Math.pow(x - circles[i].x, 2) + Math.pow(y - circles[i].y, 2)
        )
        if (distance < radius + circles[i].radius) {
          return true
        }
      }
      return false
    }
  </script>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    body {
        overflow: hidden;
        width: 100vw;
        height: 100vh;
    }
  </style>
</html>
